<template>
  <div id="app">
    <div class="container">
      <div class="header">
        <!-- 左侧按钮组 -->
        <div class="header-left">
          <el-button
            v-if="adddepPermission"
            type="primary"
            size="medium"
            @click="addDepartment()"
          >
            新增
          </el-button>
          <el-button
            v-if="editdepPermission"
            type="primary"
            size="medium"
            @click="editDepartment()"
          >
            编辑
          </el-button>
          <el-button
            v-if="deletedepPermission"
            type="primary"
            size="medium"
            @click="deleteDepartment()"
          >
            删除
          </el-button>
        </div>
        <!-- 右侧按钮组 -->
        <div class="header-right">
          <el-button
            type="primary"
            size="medium"
            icon="el-icon-plus"
            @click="addJob()"
          >
            专属岗位
          </el-button>
        </div>
      </div>
      <div class="main-content">
        <!-- 左侧组织架构树 -->
        <div class="left-panel">
          <el-tree
            ref="departmentTreeRef"
            :data="departmentTree"
            :props="defaultProps"
            node-key="DepID"
            :default-expanded-keys="defaultExpandedKeys"
            :current-node-key="currentNodeKey"
            highlight-current
            :expand-on-click-node="false"
            :height="treeHeight"
            :lazy="true"
            :load="loadNode"
            @node-click="handleNodeClick"
          >
            <span
              slot-scope="{ node }"
              class="custom-tree-node"
            >
              <span class="node-name">{{ node.label }}</span>
              <span class="node-actions">
                <i
                  class="el-icon-more"
                  style="color: black;"
                />
              </span>
            </span>
          </el-tree>
        </div>

        <!-- 右侧岗位人员表格 -->
        <div class="right-panel">
          <div class="table-header">
            <span>当前部门：{{ currentDepartment }}</span>
          </div>

          <el-table
            ref="tableRef"
            :data="tableData"
            style="width: 100%"
            empty-text="暂无数据"
            :height="treeHeight"
            :loading="isTableLoading"
            :border="true"
          >
            <el-table-column
        
              label="序号"
              width="60"
              type="index" 
              align="center" 
              :index="indexmethod"
            />
            <el-table-column
              prop="IsExclusive"
              label="岗位类型"
              width="120"
            >
              <template slot-scope="scope">
                {{ getJobTypeText(scope.row.IsExclusive) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="JobName"
              label="岗位名称"
              width="150"
            />
            <el-table-column
              prop="UserName"
              label="人员"
            />
            <el-table-column
              label="操作"
              width="150"
            >
              <template slot-scope="scope">
                <div class="operation-buttons">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleEdit(scope.row)"
                  >
                    人员设置
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    style="color: #f56c6c;"
                    @click="handleDeleteSingle(scope.row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              background
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    <AddEditdepartment
      :dialog-visible="isDepartmentEditorVisible"
      :title="title"
      :department-data="DepartmentData"
      :pdepartment-data="currentDepartmentlist"
      @close="handleDialogClose"
      @refresh="refreshTree" 
    />
    <addJob
      :dialog-visible="AddJobDialogVisible"
      :title="title"
      :department-data="DepartmentData"
      @close="jobdialogClose"
      @jobrefresh="refreshTable"
    />
    <UserSet
      :dialog-visible="UsersetDialogVisible"
      :title="title"
      :jobdep="jobdep"
      @close="usersetClose"
      @userrefresh="refreshTable"
    />
  </div>
</template>
<script>
import { GetData,BatchTableOperateRequestByCRUD} from '@/api/Hr';
import AddEditdepartment from './components/add-edit.vue';
import addJob from './components/add-job.vue';
import UserSet from './components/user-set.vue';
export default {
  components: {
    AddEditdepartment,
    addJob,
    UserSet
  },
  data() {
    return {
      departmentTree: [],
      currentDepartment: '',
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      defaultProps: {
        children: 'children',
        label: (data) => {
          return data.IsTrue !== '0' ? data.DepName + '（非实体）' : data.DepName;
        },
        isLeaf: (data) => {
          // 根据实际情况判断是否为叶子节点
          // 如果知道某个字段可以判断，就使用该字段
          // 否则默认所有节点都可以有子节点
        return !data.hasChild;
        }
      },
      isDepartmentEditorVisible: false,
      title: '',
      DepartmentData: {},
      currentDepartmentlist: {},
      defaultExpandedKeys: [],
      currentNodeKey: '',
      nodeCache: new Map(), // 缓存已加载的节点数据
        lastClickedNodeId: '', // 记录上次点击的节点ID
    isTableLoading: false, // 表格加载状态
    JobTypeText:{},
    AddJobDialogVisible: false,
    UsersetDialogVisible:false,
    jobdep:{},
    adddepPermission:true,
    editdepPermission:true,
    deletedepPermission:true,
    }
  },
  computed: {
    treeHeight() {
      // 根据窗口高度计算，比如减去头部和其他元素的高度
      return window.innerHeight - 300 + 'px';
    }
  },
  mounted() {
    this.itin();
    this.getJobType();
  },
  methods: {
     indexmethod(index) {
      return (index + 1) + (this.currentPage - 1) * (this.pageSize)
    },
     async itin() {
      try {
        const rootNodes = await this.loadRootNodes();
        this.departmentTree = rootNodes;
        console.log(this.departmentTree)
     // 设置默认选中的第一个节点
        if (rootNodes.length > 0) {
        
          this.currentNodeKey = rootNodes[0].DepID;
          this.defaultExpandedKeys = [rootNodes[0].DepID];
             this.currentDepartment =  rootNodes[0].zwSCR;
           this.$nextTick(() => {
            this.ensureCurrentNodeSelected();
          });
            if('lingma_sys_params' in rootNodes[0] ){
            this.deletedepPermission= rootNodes[0].lingma_sys_params.d
            if(rootNodes[0].lingma_sys_params.e.length===0){
             this.editdepPermission = false 
            }else{
              this.editdepPermission = true 
            }
          }
          // 加载第一个节点的表格数据
          this.loadTableData(rootNodes[0].DepID);
        }
        
      } catch (error) {
        this.$message.error("获取根节点数据失败:" + error);
      }
      // const data = {
      //   Table: [
      //     {
      //       Name: "Base_DepartInfo",
      //       Type: "数据库表",
      //       DbName: "task_demo",
      //       DISTINCT: true,
      //       Fields: [{
      //         Name: "DepCode",
      //         OrderType: "ascending",
      //         Order: 1
      //       }
      //       ]
      //     }
      //   ]
      // }
      // GetData(data, 'DA242D6EF89B69A7ED5D2728408833AB').then(res => {
      //   console.log(res)
      //   if (res.Code === 200) {
      //     const map = {};
      //     const tree = [];
      //     res.Result.data.Items.forEach(item => {
      //       map[item.DepID] = {
      //         ...item,
      //         children: []
      //       };
      //     });
      //     res.Result.data.Items.forEach(item => {
      //       const node = map[item.DepID];

      //       if (item.Prowid === '000000') {
      //         // 根节点
      //         tree.push(node);
      //       } else {
      //         // 子节点
      //         const parent = map[item.Prowid];
      //         if (parent) {
      //           parent.children.push(node);
      //         } else {
      //           // 如果找不到父节点，则作为根节点
      //           tree.push(node);
      //         }
      //       }
      //     });
      //     this.departmentTree = tree;
      //     const tableData = {
      //       Table: [
      //         {
      //           Name: "view_dep_job_userDJ",
      //           Type: "数据库视图",
      //           DbName: "task_demo",
      //           DISTINCT: true,
      //           Filter: {
      //             "Type": "and",
      //             "Filters": [
      //               {
      //                 "Type": "and",
      //                 "Filters": [
      //                   {
      //                     "Type": "cond",
      //                     "Field": "DepID",
      //                     "Operator": "equal",
      //                     "Value": null,
      //                     "ValueFun": {
      //                       "Type": "GetConstValue",
      //                       "Value": "D001"
      //                     }
      //                   }
      //                 ]
      //               }
      //             ]
      //           }
      //         }
      //       ],
      //       PageParam: {
      //         "index": 1,
      //         "size": 20
      //       }
      //     }
      //      GetData(tableData, 'DA242D6EF89B69A7ED5D2728408833AB').then(res => {
      //       console.log(res)
      //       if (res.Code === 200) {
      //         this.tableData = res.Result.data.Items;
      //         this.total = res.Result.data.TotalCount;
      //       }
      //      })
      //   }
      // })
      //   .catch(error => {
      //     this.$message.error("获取数据失败:", error);
      //   });
    },
     getJobType() {
        const data =
      {
        "Table": [
          {
            "Name": "ISExclusiveJob",
            "Type": "字典",
            "DbName": "task_demo",
            "DISTINCT": true,
            "OutputType": "Table"
          }
        ]
      }

     GetData(data, 'DA242D6EF89B69A7ED5D2728408833AB').then(res => {

      if (res.Code === 200) {
        const map = {};
        res.Result.data.Items.forEach(item => {
          map[item.val] = item.txt;
        });
        this.JobTypeText=map
      
      }

      }).catch(error => {
        console.error(error);
      });
     },
     getJobTypeText(value){
      return this.JobTypeText[value] || '未知类型';
     },
     // 确保当前节点被选中
    ensureCurrentNodeSelected() {
      if (this.currentNodeKey && this.$refs.departmentTreeRef) {
        this.$refs.departmentTreeRef.setCurrentKey(this.currentNodeKey);
        
        // 如果仍然没有选中，延迟重试
        setTimeout(() => {
          const currentNode = this.$refs.departmentTreeRef.getCurrentNode();
          if (!currentNode) {
            this.$refs.departmentTreeRef.setCurrentKey(this.currentNodeKey);
          }
        }, 200);
      }
    },
    // 加载根节点
    async loadRootNodes() {
      const data =
      {
        "hasChildField": "hasChild",
        "keyField": "DepID",
        "nodeid": "000000",
        "parentField": "Prowid",
        "type": "child",
        "Table": [
          {
            "Name": "Base_DepartInfo",
            "Type": "all",
            "DbName": "task_demo",
            "DISTINCT": true,
            "OutputType": "SelfRefData",
              "Fields": [{
               "Name": "DepCode",
               "OrderType": "ascending",
               "Order": 1
             }
             ]
          }
        ]
      }

      const res = await GetData(data, 'DA242D6EF89B69A7ED5D2728408833AB');
      if (res.Code === 200) {
        this.adddepPermission=res.Result.allowAdd
        return res.Result.data.map(item => ({
          ...item,
          children: [] // 初始化空子节点数组
        }));
      }
      return [];
    },
      // 懒加载节点数据
    async loadNode(node, resolve) {
      try {
        if (node.level === 0) {
          // 根节点已经在初始化时加载
          resolve(this.departmentTree);
        } else {
          const children = await this.loadChildNodes(node.data.DepID);
          resolve(children);
        }
      } catch (error) {
        console.error('加载节点数据失败:', error);
        resolve([]);
      }
    },
  
      // 加载子节点
    async loadChildNodes(parentId) {
      // 检查缓存
      if (this.nodeCache.has(parentId)) {
        return this.nodeCache.get(parentId);
      }

      const data = {
         "hasChildField": "hasChild",
    "keyField": "DepID",
    "nodeid":parentId ,
    "parentField": "Prowid",
    "type": "child",
        Table: [
          {
            "Name": "Base_DepartInfo",
            "Type": "数据库表",
            "DbName": "task_demo",
            "DISTINCT": true,
            "OutputType": "SelfRefData",
             "Fields": [{
               "Name": "DepCode",
               "OrderType": "ascending",
               "Order": 1
             }
             ]
          }
        ]
      };

      const res = await GetData(data, 'DA242D6EF89B69A7ED5D2728408833AB');
      if (res.Code === 200) {
        const children = res.Result.data.map(item => ({
          ...item,
          children: [] // 初始化空子节点数组
        }));
        
        // 缓存结果
        this.nodeCache.set(parentId, children);
        return children;
      }
      return [];
    },
     // 加载表格数据
    async loadTableData(depId) {
      try {
        const tableData = {
          Table: [
            {
              Name: "view_dep_job_userDJ",
              Type: "数据库视图",
              DbName: "task_demo",
              DISTINCT: true,
              Filter: {
                "Type": "and",
                "Filters": [
                  {
                    "Type": "and",
                    "Filters": [
                      {
                        "Type": "cond",
                        "Field": "DepID",
                        "Operator": "equal",
                        "Value": null,
                        "ValueFun": {
                          "Type": "GetConstValue",
                          "Value": depId
                        }
                      }
                    ]
                  }
                ]
              }
            }
          ],
          PageParam: {
            "index": this.currentPage,
            "size": this.pageSize
          }
        };
        
        const res = await GetData(tableData, 'DA242D6EF89B69A7ED5D2728408833AB');
        if (res.Code === 200) {
          this.tableData = res.Result.data.Items;
          this.total = res.Result.data.Count;
        }
      } catch (error) {
        console.error('加载表格数据失败:', error);
        this.tableData = [];
        this.total = 0;
      }
    },
      // 根据部门ID获取部门名称
    getDepartmentName(depId) {
      // 在树中查找部门名称
      const findDepartmentName = (nodes, targetId) => {
        for (const node of nodes) {
          if (node.DepID === targetId) {
            return node.DepName;
          }
          if (node.children && node.children.length > 0) {
            const result = findDepartmentName(node.children, targetId);
            if (result) return result;
          }
        }
        return '';
      };
      
      return findDepartmentName(this.departmentTree, depId) || '未知部门';
    },
    addDepartment() {
      // 方法1：通过 ref 获取当前选中节点
      if (this.$refs.departmentTreeRef) {
        const currentNode = this.$refs.departmentTreeRef.getCurrentNode();
        if (currentNode) {
          this.isDepartmentEditorVisible = true;
          this.title = '新增部门';
          this.DepartmentData = {};
          this.currentDepartmentlist = currentNode;
        } else {
          console.log('没有选中任何节点');
          this.currentDepartmentlist = {};
        }
      }

    },
    editDepartment() {
      if (this.$refs.departmentTreeRef) {
        const currentNode = this.$refs.departmentTreeRef.getCurrentNode();
        if (currentNode) {
          this.isDepartmentEditorVisible = true;
          this.title = '编辑部门';
          this.DepartmentData = currentNode;
        } else {
          console.log('没有选中任何节点');
          this.DepartmentData = {};
        }
      }
    },
    handleDialogClose() {
      this.isDepartmentEditorVisible = false;
    },
    jobdialogClose(){
      this.AddJobDialogVisible = false;
    },
    usersetClose(refreshState){
      this.UsersetDialogVisible = false;
      if(refreshState){
         this.loadTableData(this.currentNodeKey);
      }
    },
    refreshTable(){
       this.AddJobDialogVisible = false;
      this.loadTableData(this.currentNodeKey);
    },
    handleNodeClick(data, node) {
      // 原有的点击事件逻辑
        // 如果是同一个节点，直接返回，不重复加载
  if (this.lastClickedNodeId === data.DepID) {
    this.currentNodeKey = data.DepID;
    this.$nextTick(() => {
      if (this.$refs.departmentTreeRef) {
        this.$refs.departmentTreeRef.setCurrentKey(this.currentNodeKey);
      }
    });
    return;
  }
  this.lastClickedNodeId = data.DepID;
  this.currentNodeKey = data.DepID;
   if('lingma_sys_params' in data ){
            this.deletedepPermission= data.lingma_sys_params.d
            if(data.lingma_sys_params.e.length===0){
             this.editdepPermission = false 
            }else{
              this.editdepPermission = true 
            }
          }
          else{
              this.deletedepPermission=true
              this.editdepPermission=true
          }
      const tableData = {
        Table: [
          {
            Name: "view_dep_job_userDJ",
            Type: "数据库视图",
            DbName: "task_demo",
            DISTINCT: true,
            Filter: {
              "Type": "and",
              "Filters": [
                {
                  "Type": "and",
                  "Filters": [
                    {
                      "Type": "cond",
                      "Field": "DepID",
                      "Operator": "equal",
                      "Value": null,
                      "ValueFun": {
                        "Type": "GetConstValue",
                        "Value": data.DepID
                      }
                    }
                  ]
                }
              ]
            }
          }
        ],
        PageParam: {
          "index": 1,
          "size": 20
        }
      }
      GetData(tableData, 'DA242D6EF89B69A7ED5D2728408833AB').then(res => {
        console.log(res)
        if (res.Code === 200) {
          this.currentDepartment = data.zwSCR
          this.tableData = res.Result.data.Items;
          this.total = res.Result.data.Count;
        }
      }).catch(error => {
        console.error(error);
      });
    },
     async refreshTree(operationInfo) {
    try {
       if (operationInfo.parentData && operationInfo.parentData.DepID) {
      this.nodeCache.delete(operationInfo.parentData.DepID);
    }
    
      if (operationInfo.type === 'add') {
        // 新增部门后的刷新逻辑
        await this.handleAddRefresh(operationInfo);
      } else if (operationInfo.type === 'edit') {
        // 编辑部门后的刷新逻辑
        await this.handleEditRefresh(operationInfo);
      } else if (operationInfo.type === 'delete') {
        // 删除部门后的刷新逻辑
        await this.handleDeleteRefresh(operationInfo);
      }
      
    } catch (error) {
      console.error('刷新树结构失败:', error);
      this.$message.error('刷新数据失败');
    }
  },
 // 处理新增刷新
async handleAddRefresh(operationInfo) {
  const { parentData } = operationInfo;
  
  if (!parentData || !parentData.DepID) return;
  
  console.log('开始刷新父节点:', parentData.DepID, parentData.DepName);
  
  // 清除父节点的缓存
  this.nodeCache.delete(parentData.DepID);
  
  if (this.$refs.departmentTreeRef) {
    const parentNode = this.$refs.departmentTreeRef.getNode(parentData.DepID);
    if (parentNode) {
      try {
        // 直接加载新的子节点数据
        const newChildren = await this.loadChildNodes(parentData.DepID);
        console.log('加载到的新子节点:', newChildren);
        
        // 使用 updateKeyChildren 直接更新子节点
        this.$refs.departmentTreeRef.updateKeyChildren(parentData.DepID, newChildren);
        
        // 确保父节点是展开状态
        if (!parentNode.expanded) {
          parentNode.expanded = true;
        }
        
        // 强制更新视图
        this.$forceUpdate();
  
      } catch (error) {
        console.error('刷新子节点失败:', error);
        this.$message.error('刷新数据失败');
      }
    } else {
      console.warn('未找到父节点:', parentData.DepID);
    }
  }
},
  
  // 处理编辑刷新
  async handleEditRefresh(operationInfo) {
    const { data } = operationInfo;
    
    // 更新树中对应节点的数据
    if (this.$refs.departmentTreeRef) {
      const node = this.$refs.departmentTreeRef.getNode(data.DepID);
      if (node) {
        // 更新节点数据
        Object.assign(node.data, data);
        
        // 手动触发节点更新
        this.$refs.departmentTreeRef.updateKeyChildren(data.DepID, node.childNodes || []);
        
        // 如果当前选中的是这个节点，更新相关显示
        if (this.currentNodeKey === data.DepID) {
          this.currentDepartment = data.zwSCR;
          // 重新加载表格数据
          this.loadTableData(data.DepID);
        }
      }
    }
  },
  // 处理删除刷新
async handleDeleteRefresh(operationInfo) {
  const { data: deletedData } = operationInfo;
  
  await new Promise(resolve => setTimeout(resolve, 500));
  
  // 清除相关缓存

  
  if (this.$refs.departmentTreeRef) {
    try {
      // 方法1：通过父节点来删除子节点
      const tree = this.$refs.departmentTreeRef;
      const deletedNode = tree.getNode(deletedData.DepID);
      
      if (deletedNode && deletedNode.parent) {
        const parentNode = deletedNode.parent;
        const parentData = parentNode.data;
         this.nodeCache.delete(parentData.DepID);
        console.log('找到父节点:', parentData.DepID, parentData.DepName);
        
        // 从父节点的 children 中移除被删除的节点
        if (parentData.children) {
          const index = parentData.children.findIndex(child => child.DepID === deletedData.DepID);
          if (index > -1) {
            parentData.children.splice(index, 1);
            console.log('从父节点children中移除成功');
          }
        }
        
        // 更新父节点的子节点
        const newChildren = await this.loadChildNodes(parentData.DepID);
        tree.updateKeyChildren(parentData.DepID, newChildren);
        
        console.log('父节点更新完成，新子节点数量:', newChildren.length);
        
        // 如果删除的是当前选中的节点，选择父节点
        if (this.currentNodeKey === deletedData.DepID) {
          this.currentNodeKey = parentData.DepID;
          this.currentDepartment = parentData.zwSCR || parentData.DepName;
          
          this.$nextTick(() => {
            this.ensureCurrentNodeSelected();
            this.loadTableData(parentData.DepID);
          });
        }
      } else {
        // 如果找不到节点，可能是根节点，重新加载整个树
        console.log('未找到节点或节点无父节点，重新加载整棵树');

      }
    } catch (error) {
      console.error('删除刷新失败:', error);
    
    }
  }
},
  // 重新加载节点的子节点
  async reloadNodeChildren(node) {
    if (!node) return;
    
    const children = await this.loadChildNodes(node.data.DepID);
    this.$refs.departmentTreeRef.updateKeyChildren(node.data.DepID, children);
  },
  
  // 查找树节点
  findTreeNode(nodes, depId) {
    for (const node of nodes) {
      if (node.DepID === depId) {
        return node;
      }
      if (node.children && node.children.length > 0) {
        const found = this.findTreeNode(node.children, depId);
        if (found) return found;
      }
    }
    return null;
  },
   deleteDepartment() {
    if (this.$refs.departmentTreeRef) {
      const currentNode = this.$refs.departmentTreeRef.getCurrentNode();
      if (currentNode) {
        this.$confirm('确定要删除这个部门吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            // 调用删除API
            const data = [{
              TableName: 'task_demo@Base_DepartInfo',
              CrudModel: {
                Added: [],
                Changed: [],
                Deleted: [{
                  rowid: currentNode.rowid
                }]
              }
            }];
            

            BatchTableOperateRequestByCRUD(data, 'DA242D6EF89B69A7ED5D2728408833AB').then(result=>{
                 if (result.success) {
              this.$message.success('删除成功');
              // 触发刷新
              this.refreshTree({
                type: 'delete',
                data: currentNode,
                parentData: this.findParentNode(currentNode.DepID) 
              });
              
            } else {
              this.$message.error('删除失败');
            }
            })
         
          } catch (error) {
            this.$message.error('删除失败');
            console.error('删除失败:', error);
          }
        }).catch(() => {
          // 用户取消删除
        });
      } else {
        this.$message.warning('请先选择一个部门');
      }
    }
  },
  
// 查找父节点
findParentNode(depId) {
  const findParent = (nodes, targetId, parent = null) => {
    for (const node of nodes) {
      if (node.DepID === targetId) {
        return parent;
      }
      if (node.children && node.children.length > 0) {
        const result = findParent(node.children, targetId, node);
        if (result) return result;
      }
    }
    return null;
  };
  
  return findParent(this.departmentTree, depId);
},
  // 每页条数改变
  handleSizeChange(newSize) {
    console.log('每页条数改变:', newSize);
    this.pageSize = newSize;
    this.loadCurrentPageData();
  },
  
  // 当前页码改变
  handleCurrentChange(newPage) {
    console.log('页码改变:', newPage);
    this.currentPage = newPage;
    this.loadCurrentPageData();
  },
   // 加载当前页数据
  async loadCurrentPageData() {
    if (this.$refs.departmentTreeRef) {
      const currentNode = this.$refs.departmentTreeRef.getCurrentNode();
      if (currentNode) {
        await this.loadTableData(currentNode.DepID);
      }
    }
  },
  addJob(){
    if (this.$refs.departmentTreeRef) {
      const currentNode = this.$refs.departmentTreeRef.getCurrentNode();
      if (currentNode) {
           this.DepartmentData = currentNode;
    this.AddJobDialogVisible = true;
      }else {
        this.$message.warning('请先选择一个部门');
      }
    }

  },
  handleDeleteSingle(row){
    if(row.IsExclusive===0){ return this.$message.warning('不能删除通用岗位'); }
    if(row.UserID ===null || row.UserID ===undefined || row.UserID===''){
    this.$confirm('确定要删除这条岗位数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const data = [{
        TableName: 'task_demo@Base_JobInfo', // 根据实际表名调整
        CrudModel: {
          Added: [],
          Changed: [],
          Deleted: [{
            ID: row.JID
          }]
        }
      }];
      
      const result = await BatchTableOperateRequestByCRUD(data, 'DA242D6EF89B69A7ED5D2728408833AB');
      if (result.success) {
        this.$message.success('删除成功');
        this.refreshTable();
      } else {
        this.$message.error('删除失败');
      }
    } catch (error) {
      this.$message.error('删除失败');
      console.error('删除岗位数据失败:', error);
    }
  }).catch(() => {
    // 用户取消删除
  });
}else{
  this.$message.warning('该条岗位数据已分配给其他用户，不能删除');
  }},
  handleEdit(row){
    this.jobdep=row
    this.title='人员设置'
this.UsersetDialogVisible=true
  }
  }
}
</script>
<style>
.container {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.header-left {
  display: flex;
  gap: 10px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.main-content {
  display: flex;
  gap: 20px;
  padding: 15px;
}

.left-panel {
  width: 300px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.left-panel h3 {
  margin-bottom: 15px;
  color: black;
  font-size: 16px;
  font-weight: 500;
}

.right-panel {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  padding: 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  text-align: left;
}

.pagination {
  padding: 15px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #ebeef5;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 100%;
  cursor: pointer;
}

.custom-tree-node .node-name {
  flex: 1;
  font-size: 18px;
  text-align: left;
}

.custom-tree-node .node-actions {
  display: flex;
  gap: 5px;
}

.el-tree {
  color: black;
}

.el-tree-node__content {
  height: 36px;
}

.el-tree-node:focus>.el-tree-node__content {
  background-color: #0d6efd;
}

.el-tree-node.is-current>.el-tree-node__content {
  background-color: #0d6efd !important;
  color: white !important;
}

.operation-buttons {
  display: flex;
  gap: 8px;
}

.el-button--mini {
  padding: 5px 10px;
}
</style>